//
//  DataFillView.swift
//  ShiZhe
//
//  Created by 陈卿伟 on 16/9/1.
//  Copyright © 2016年 陈卿伟. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class DataFillView: UIView {
    var beGoodAtTF:UITextField!//填写擅长的领域的白框
    var plusIconG:UIButton!//添加选项的按钮 擅长
    var scrollG:UIScrollView!//在擅长领域那里添加的scrollview
    var nextButton:UIButton!//下一步按钮
    var itemX:CGFloat = 16//记录已经选择的item的总长度 以便计算下一个item的x
    var buttonTag:Int = 0//记录button的tag
    var tagArr:Array<Int> = []//记录现在总共有的item数量 数据是每个item的tag
    var menuID:Array<String> = []
    
    override init(frame: CGRect) {
        beGoodAtTF = UITextField()
        plusIconG = UIButton()
        scrollG = UIScrollView()
        nextButton = UIButton()
        super.init(frame: frame)
        self.createRedBG()
        self.createRedLineAndHintLabel()
        self.createBeGoodAtView()
        self.createNextButton()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        beGoodAtTF.resignFirstResponder()
    }
    
    
    //红色的幕布  和 提示文字
    func createRedBG(){
        let redView = UIView(frame: CGRect(x: 0,y: 0,width: WidthAPP,height: 55*SCALEH))
        redView.backgroundColor = UIColor.redColor()
        self.addSubview(redView)
        
        let hintLabel = UILabel(frame: CGRect(x: 20*SCALEW,y: 0,width: WidthAPP-40*SCALEW,height: 55*SCALEH))
        hintLabel.text = "您为首次登录，为了更好的帮您匹配行友的提问和对您有用的回答，请稍微花几分钟填写以下资料。"
        hintLabel.numberOfLines = 2
        hintLabel.font = BaseFunc.getLightFont(14)
        hintLabel.textAlignment = .Left
        hintLabel.textColor = UIColor.whiteColor()
        self.addSubview(hintLabel)
    }
    
    
    //创建红色小长条和文字
    func createRedLineAndHintLabel(){
        let redLine = UIView(frame: CGRect(x: 21*SCALEW,y: 64*SCALEH,width: 3*SCALEW,height: 12*SCALEH))
        redLine.backgroundColor = UIColor.redColor()
        self.addSubview(redLine)
        
        let hintLabel = UILabel(frame: CGRect(x: 31*SCALEW,y: 64*SCALEH,width: 300*SCALEW,height: 12*SCALEH))
        hintLabel.textAlignment = .Left
        hintLabel.textColor = UIColor.blackColor()
        hintLabel.text = "我们会为您配置您所关注的标签的优质内容。"
        hintLabel.font = BaseFunc.getCustomFont(13)
        self.addSubview(hintLabel)
    }
    
    
    //创建我对以下领域颇有建树的白框
    func createBeGoodAtView(){
        beGoodAtTF.frame = CGRect(x: 0, y: 86*SCALEH, width: WidthAPP, height: 50*SCALEH)
        beGoodAtTF.backgroundColor = UIColor.whiteColor()
        beGoodAtTF.placeholder = "请选择您要关注的标签"
        beGoodAtTF.font = BaseFunc.getCustomFont(14)
        beGoodAtTF.leftView = UIView(frame: CGRect(x: 0,y: 0,width: 13,height: 1))
        beGoodAtTF.leftViewMode = .Always
        beGoodAtTF.rightView = UIView(frame: CGRect(x: WidthAPP-13,y: 0,width: 13,height: 1))
        beGoodAtTF.rightViewMode = .Always
        beGoodAtTF.tintColor = UIColor.clearColor()
        self.addSubview(beGoodAtTF)
    }
    
    //创建下一步按钮
    func createNextButton(){
        nextButton.frame = CGRect(x: 33*SCALEW, y: 151*SCALEH, width: 309*SCALEW, height: 50*SCALEH)
        nextButton.titleLabel?.font = BaseFunc.getCustomFont(18)
        nextButton.setTitle("下一步", forState: UIControlState())
        nextButton.backgroundColor = UIColor.blackColor()
        nextButton.layer.cornerRadius = 5
        self.addSubview(nextButton)
    }
    
    //添加scroll到GTF上面
    func addScrollViewToBeGoodTF(){
        scrollG.frame = CGRect(x: 0, y: 0, width: WidthAPP, height: 50*SCALEH)
        scrollG.showsVerticalScrollIndicator = false
        scrollG.showsHorizontalScrollIndicator = false
        scrollG.bringSubviewToFront(beGoodAtTF)//保证在TF获得焦点的时候，scroll也能滑动
        beGoodAtTF.addSubview(scrollG)
        
        plusIconG.backgroundColor = Theme.GrayColor
        plusIconG.setTitle("➕", forState: UIControlState())
        plusIconG.layer.cornerRadius = 14*SCALEW
        plusIconG.addTarget(self, action: #selector(self.plusIconClick(_:)), forControlEvents: .TouchUpInside)
        plusIconG.tag = 677
        scrollG.addSubview(plusIconG)
    }
    
    //添加感兴趣的选项，的点击  BeGoodTF
    func addItemToBeGoodTF(text:String,mune_id:String){
        if itemX == 16{
            self.addScrollViewToBeGoodTF()//在添加item的时候再将scroll添加进来 要不然就覆盖住了TF 无法点击了
        }
        let itemButton = UIButton()
        itemButton.setTitle(text, forState: UIControlState())
        itemButton.titleLabel?.font = BaseFunc.getCustomFont(15)
        itemButton.backgroundColor = Theme.YellowColor
        itemButton.layer.cornerRadius = 15
        itemButton.addTarget(self, action: #selector(itemButtonClick(_:)), forControlEvents: .TouchDownRepeat)
        let constraint = CGSize(width: 1000, height: 1000)
        let size = text.boundingRectWithSize(constraint, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes:NSDictionary(object:UIFont(name: "Heiti SC", size: 15*SCALEW)!, forKey: NSFontAttributeName as NSCopying) as? [String : AnyObject],context: nil)
        itemButton.frame = CGRect(x: itemX, y: 10, width: size.width+20*SCALEW, height: 30*SCALEH)
        itemButton.tag = buttonTag+660//判断这是第几个item
        self.scrollG.addSubview(itemButton)
        
        self.menuID.insert(mune_id, atIndex: self.menuID.count)
        print(menuID)
        self.tagArr.append(buttonTag)
        self.buttonTag += 1
        self.itemX += (size.width+20*SCALEW+10*SCALEW)
        
        plusIconG.frame = CGRect(x: itemX, y: 11*SCALEH, width: 28*SCALEW, height: 28*SCALEW)
        scrollG.contentSize = CGSize(width: itemX+48*SCALEW, height: 50*SCALEH)
        scrollG.scrollRectToVisible(CGRect(x: itemX-WidthAPP+48*SCALEW, y: 0, width: WidthAPP, height: 50*SCALEH), animated: true)
    }
}

//MARK:--点击事件
extension DataFillView{
    //选择之后的选项的点击事件
    func itemButtonClick(sender:UIButton){
        let tag = sender.tag-660
        var remI = 0//记录tagArr循环结束的时候应该删除第几个index的项
        //循环总共有的tag数量
        for i in 0..<self.tagArr.count{
            //根据下标，取出这个下标的tag  也就是现在的button的tag
            let t = self.tagArr[i]
            //如果取出的tag和点击的tag相同，就将这个tag保存下来 等循环结束的时候，将其删除，不能再循环中删除，这样数据会错乱
            if t  == tag{
                remI = i
                continue
                //因为是要将item左移，所以tag比我们要删除的tag小的话不考虑，因为不需要移动它们
            }else if t>tag{
                let buttonItem = self.viewWithTag(660+t) as! UIButton
                UIView.animateWithDuration(0.2, delay: 0, options: .CurveEaseOut, animations: {
                    buttonItem.frame.origin.x -= (sender.frame.size.width+10*SCALEW)
                    }, completion: nil)
            }
        }
        //在循环结束之后，将tagArr中要删除的项删除
        self.tagArr.removeAtIndex(remI)
        self.deleteItemAlamofire(remI)
        
        //因为删除了那一项，所以下一个item的位置的X也要删除那一项的宽度，加上它们的间隔
        self.itemX -= (sender.frame.size.width+10*SCALEW)
        UIView.animateWithDuration(0.2, delay: 0, options: .CurveEaseOut, animations: {
            sender.transform = CGAffineTransformMakeScale(0.1, 0.1)
            sender.alpha = 0
            self.plusIconG.frame = CGRect(x: self.itemX, y: 11*SCALEH, width: 28*SCALEW, height: 28*SCALEW)
            self.scrollG.contentSize = CGSize(width: self.itemX+48*SCALEW, height: 50*SCALEH)
            }) { (end) in
                sender.removeFromSuperview()
                if self.itemX == 16{
                    self.beGoodAtTF.textAlignment = .Left
                    self.beGoodAtTF.placeholder = "行友们对这一领域提问会第一时间推送给您"
                    self.plusIconG.removeFromSuperview()
                    self.scrollG.removeFromSuperview()
                    //当item总的会去挡到placeholder的时候，就将placeholder设为“” 删除到没挡到的时候，就让它回来
                }else if self.itemX < (WidthAPP/3*2 - 30*SCALEW){
                    self.beGoodAtTF.textAlignment = .Right
                    self.beGoodAtTF.placeholder = "双击可删除选项"
                }
        }
    }
    
    
    //➕按钮点击事件
    func plusIconClick(sender:UIButton){
        beGoodAtTF.becomeFirstResponder()
    }
}

//MARK:--Alamofire
extension DataFillView{
    //删除已关注的item项
    func deleteItemAlamofire(row:Int){
        let menuid = self.menuID[row]
        let parameters = ["menu_id":menuid]
        let headers = ["token":OperateUserDefaults.takeUserInfo().token]
        Alamofire.request(.POST, "http://srxapp.zhekd.com/ios.php/Menu/dele_menu", parameters: parameters, encoding: .JSON, headers: headers).responseJSON { (data) in
            let json = JSON(data: data.data!)
            print(json)
            self.menuID.removeAtIndex(row)
        }
    }
}















